package com.lcke.system.service;

import com.lcke.common.login.User;
import com.lcke.system.dao.UserMapper;
import com.lcke.system.model.SystemUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public SystemUser findByNameAndPassword(SystemUser param) {
        SystemUser result = null;
        List<SystemUser> systemUsers = userMapper.findByNameAndPassword(param);
        // 没有机构角色随机选择一个
        if (systemUsers.size() > 0) {
            SystemUser systemUser = systemUsers.get(0);
            systemUser.setRoles(systemUsers);
            result = systemUser;
        }
        // 有对应的用户
        if (result != null) {
            // 更新登录时间和次数
            Boolean success = this.updateLoginInfo(result);
        }
        return result;
    }

    /**
     * todo 丹城三小不需要切换身份
     */
    public SystemUser switchRoleByName(User param) {
        SystemUser result = null;
        List<SystemUser> systemUsers = userMapper.findByNameAndPassword(param);
        for (SystemUser systemUser : systemUsers) {
            // 切换一个身份
            if (param.getUserId().equals(String.valueOf(systemUser.getUserId()))) {
                systemUser.setRoles(systemUsers);
                result = systemUser;
            }
        }
        if (null == result && systemUsers.size() > 0) {
            SystemUser systemUser = systemUsers.get(0);
            systemUser.setRoles(systemUsers);
            result = systemUser;
        }
        // 有对应的用户
        if (result != null) {
            // 更新登录时间和次数
            Boolean success = this.updateLoginInfo(result);
        }
        return result;
    }

    private Boolean updateLoginInfo(SystemUser systemUser) {
        log.info(systemUser.getUserName() + " 登录次数 + 1 ");
        return null;
    }
}
